﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
using CWM.Skinn;

public class SkinnProCustomInspector
{
    public Transform cc3ExportCharacter;
    public Transform bodyRoot;
    public SkinnedMeshRenderer bodyMesh;
    public SkinnedMeshRenderer eyeMesh;
    public SkinnedMeshRenderer teethMesh;
    public SkinnedMeshRenderer tongueMesh;

    public BlendshapeController blendshapeController;
    public List<SkinnedMeshRenderer> subMeshesList;
    public Transform fixSuperRoot; //fixRootsList.parent
    public List<Transform> fixRootsList;
    public BlendShapesStructTemplate structTemplate; //表情结构模板

    private bool isSplite = false; //分割SubMesh步骤是否完成
    private bool isExtract = false; //提取BlendShapes步骤是否完成
    private bool shownOverrideWindow = false; //是否操作过重写窗口

    private bool showInfo = true;
    private bool autoMode = false;
    private bool needClear = false; //自动纠正后是否清理临时物体
    private float autoProgress = 0;
    private CC3BlendShapesFixDataAsset fixConfig;

    private List<Vector3> bonePositionsList; //根骨默认位置
    private List<Vector3> boneRotationsList; //根骨默认角度

    public SkinnProCustomInspector()
    {
        subMeshesList = new List<SkinnedMeshRenderer>();
        fixRootsList = new List<Transform>();
        bonePositionsList = new List<Vector3>();
        boneRotationsList = new List<Vector3>();
    }

    public void AutoExe()
    {
        using (var record = new SkinnProCustomUtility.TimeRecord("自动执行"))
        {
            SkinnProCustomUtility.DisplayProgressBar(true, title: "获取模型信息", progress : 0f);
            {
                GetCharacterStructInfos(); //1.获取信息
            }

            SkinnProCustomUtility.DisplayProgressBar(true, title: "分割Submesh", progress: 0.125f);
            {
                SplitSubMesh(); //2.分割Submesh
            }
            
            SkinnProCustomUtility.DisplayProgressBar(true, title: "提取BlendShapes", progress : 0.25f);
            {
                if (subMeshesList == null || subMeshesList.Count == 0)
                {
                    subMeshesList = blendshapeController.GetComponentsInChildren<SkinnedMeshRenderer>(true).ToList();
                }
                ExtractAllBlendShapes(); //3.提取BlendShapes
            }

            SkinnProCustomUtility.DisplayProgressBar(true, title: "创建结构模板", progress: 0.375f);
            {
                CreateStructTemplate(); //4.创建结构模板
            }

            SkinnProCustomUtility.DisplayProgressBar(true, title: "烘焙一个A52", progress: 0.5f);
            {
                BakeA52TongueOut(); //烘焙一个A52
            }

            SkinnProCustomUtility.DisplayProgressBar(true, title: "移除除了AXX开头的表情", progress: 0.625f);
            {
                RemoveExceptA_XX(); //移除除了AXX开头的表情
            }

            SkinnProCustomUtility.DisplayProgressBar(true, title: "同步其他部位表情结构", progress: 0.75f);
            {
                SyncBlendShapesFromTemplate(); //同步其他部位表情结构
            }

            SkinnProCustomUtility.DisplayProgressBar(true, title: "根据纠正配置纠正表情", progress: 0.875f);
            {
                FixByDataConfig(); //根据纠正配置纠正表情
            }

            SkinnProCustomUtility.DisplayProgressBar(true, title: "合并及剔除BlendShapes信息", progress: 0.95f);
            {
                CombineHeadMeshes();
                ClearBodyBlendShapes();
                CombineBodyMeshes();
            }

            if (needClear)
            {
                SkinnProCustomUtility.DisplayProgressBar(true, title: "清理临时物体", progress: 1f);
                {
                    ClearTemp();
                }
            }

            SkinnProCustomUtility.DisplayProgressBar(false);
        }
    }

    /// <summary>
    /// 绘制整体面板结构
    /// </summary>
    public void DrawInspector()
    {
        EditorGUILayout.BeginHorizontal();
        {
            cc3ExportCharacter = EditorGUILayout.ObjectField("从CC3导出的角色模型:", cc3ExportCharacter, typeof(Transform), SkinnProCustomUtility.ObjectFieldOption()) as Transform;

            if (cc3ExportCharacter == null)
            {
                SkinnProCustomUtility.DrawColorLabel("请从Scene中指定一个从CC3导出的角色模型（Unpack）", Color.yellow);
                EditorGUILayout.EndHorizontal();

                return;
            }

            if (cc3ExportCharacter != null)
            {
                if (!SkinnProCustomUtility.IsNotPrefab(cc3ExportCharacter.gameObject))
                {
                    cc3ExportCharacter = null;
                    EditorGUILayout.EndHorizontal();

                    return;
                }
            }

            if (GUILayout.Button("1.获取信息"))
            {
                GetCharacterStructInfos();
            }

            if (GUILayout.Button("还原Pose"))
            {
                ResetBonesInfo();
            }
        }
        EditorGUILayout.EndHorizontal();

        autoMode = EditorGUILayout.Toggle("自动执行？:", autoMode);
        if (autoMode)
        {
            DrawAutoMode();

            GUI.enabled = false;
        }

        DrawCharacterStructInfos();
        DrawOperationArea();
    }

    private void DrawAutoMode()
    {
        EditorGUILayout.BeginHorizontal();
        {
            fixConfig = EditorGUILayout.ObjectField("纠正配置:", fixConfig, typeof(CC3BlendShapesFixDataAsset)) as CC3BlendShapesFixDataAsset;

            if (fixConfig == null)
            {
                SetEnable(false);
            }

            needClear = EditorGUILayout.Toggle("执行完成后是否清理临时物体？:", needClear);
        }
        EditorGUILayout.EndHorizontal();

        if (GUILayout.Button("自动修复"))
        {
            AutoExe();
        }

        EditorGUILayout.Slider("自动执行进度", autoProgress, 0, 100);

        SetEnable(true);
    }

    private void ProgressUpdate()
    {
        autoProgress += 10f;
    }

    private void SetEnable(bool state)
    {
        if (autoMode)
        {
            GUI.enabled = false;

            return;
        }

        GUI.enabled = state;
    }

    private void GetCharacterStructInfos()
    {
        bodyRoot = cc3ExportCharacter.Find(SkinnProCustomConfig.BodyRoot);
        GetBonesDefaultInfo();

        Transform body = cc3ExportCharacter.Find("CC_Base_Body");
        if (body)
        {
            bodyMesh = body.GetComponent<SkinnedMeshRenderer>();
        }

        Transform eye = cc3ExportCharacter.Find(SkinnProCustomConfig.EyeMesh);
        if (eye)
        {
            eyeMesh = eye.GetComponent<SkinnedMeshRenderer>();
        }

        Transform teeth = cc3ExportCharacter.Find(SkinnProCustomConfig.TeethMesh);
        if (teeth)
        {
            teethMesh = teeth.GetComponent<SkinnedMeshRenderer>();
        }

        Transform tongue = cc3ExportCharacter.Find(SkinnProCustomConfig.TongueMesh);
        if (tongue)
        {
            tongueMesh = tongue.GetComponent<SkinnedMeshRenderer>();
        }

        ProgressUpdate();
    }

    /// <summary>
    /// 绘制角色结构信息
    /// </summary>
    private void DrawCharacterStructInfos()
    {
        showInfo = EditorGUILayout.Foldout(showInfo, "模型详细信息：");
        if (!showInfo)
        {
            return;
        }

        bodyRoot = EditorGUILayout.ObjectField("\t身体骨骼Root：", bodyRoot, typeof(Transform), SkinnProCustomUtility.ObjectFieldOption()) as Transform;
        bodyMesh = EditorGUILayout.ObjectField("\t身体蒙皮：", bodyMesh, typeof(SkinnedMeshRenderer), SkinnProCustomUtility.ObjectFieldOption()) as SkinnedMeshRenderer;
        eyeMesh = EditorGUILayout.ObjectField("\t眼睛蒙皮：", eyeMesh, typeof(SkinnedMeshRenderer), SkinnProCustomUtility.ObjectFieldOption()) as SkinnedMeshRenderer;
        teethMesh = EditorGUILayout.ObjectField("\t牙齿蒙皮：", teethMesh, typeof(SkinnedMeshRenderer), SkinnProCustomUtility.ObjectFieldOption()) as SkinnedMeshRenderer;
        tongueMesh = EditorGUILayout.ObjectField("\t舌头蒙皮：", tongueMesh, typeof(SkinnedMeshRenderer), SkinnProCustomUtility.ObjectFieldOption()) as SkinnedMeshRenderer;

        EditorGUILayout.BeginHorizontal();
        {
            if (bodyMesh == null)
            {
                SkinnProCustomUtility.DrawColorLabel("\tbodyMesh为空不可进行分割", Color.yellow);
                SetEnable(false);
            }
            EditorGUILayout.BeginHorizontal();
            {
                if (GUILayout.Button("2.分割SubMesh"))
                {
                    SplitSubMesh();
                }

                if (GUILayout.Button("若已完成了步骤2 通过手动赋值来进行下一步", SkinnProCustomUtility.ButtonOption()))
                {
                    isSplite = true;
                }
            }
            EditorGUILayout.EndHorizontal();
            SetEnable(true);
        }
        EditorGUILayout.EndHorizontal();
    }

    /// <summary>
    /// 切割子Mesh并获取BlendShapeController
    /// </summary>
    private void SplitSubMesh()
    {
        Selection.objects = GetVaildBodyPartObjs();
        using (var record = new SkinnProCustomUtility.TimeRecord("切割SubMesh"))
        {
            SkinnProCustomMain.SplitSubMeshes();
        }

        var selects = Selection.objects;
        var splitsList = new List<GameObject>();
        for (int i = 0; i < selects.Length; i++)
        {
            if (!(selects[i] is GameObject))
            {
                continue;
            }

            var go = selects[i] as GameObject;
            if (go.name.Contains(SkinnProCustomConfig.SplitSuffix))
            {
                splitsList.Add(go);
            }
        }

        GameObject splitRoot = new GameObject(cc3ExportCharacter.name + "_BlendshapeController");
        splitRoot.transform.SetParent(cc3ExportCharacter);
        splitRoot.transform.localPosition = Vector3.zero;

        for (int i = splitsList.Count - 1; i >= 0; i--) //把13个部位整合在一起 倒序 防止destroy出现索引错误
        {
            var childs = splitsList[i].transform.GetAllChildren();
            for (int j = 0; j < childs.Count; j++)
            {
                childs[j].SetParent(splitRoot.transform);
            }

            GameObject.DestroyImmediate(splitsList[i]);
        }

        blendshapeController = splitRoot.gameObject.AddComponent<BlendshapeController>();
        subMeshesList = blendshapeController.GetComponentsInChildren<SkinnedMeshRenderer>(true).ToList();
        isSplite = true;

        ProgressUpdate();
    }

    /// <summary>
    /// 绘制操作区域
    /// </summary>
    private void DrawOperationArea()
    {
        if (!isSplite)
        {
            return;
        }

        blendshapeController = EditorGUILayout.ObjectField("BlendShape总控制器：", blendshapeController, typeof(BlendshapeController), SkinnProCustomUtility.ObjectFieldOption()) as BlendshapeController;
        if (blendshapeController == null)
        {
            SetEnable(false);
        }
        EditorGUILayout.BeginHorizontal();
        {
            if (GUILayout.Button("3.提取所有BlendShapes"))
            {
                if (subMeshesList == null || subMeshesList.Count == 0)
                {
                    subMeshesList = blendshapeController.GetComponentsInChildren<SkinnedMeshRenderer>(true).ToList();
                }

                ExtractAllBlendShapes();
            }

            if (GUILayout.Button("若已完成了步骤3 通过手动赋值来进行下一步", SkinnProCustomUtility.ButtonOption()))
            {
                if (subMeshesList == null || subMeshesList.Count == 0)
                {
                    subMeshesList = blendshapeController.GetComponentsInChildren<SkinnedMeshRenderer>(true).ToList();
                }

                isExtract = true;
            }
        }
        EditorGUILayout.EndHorizontal();
        SetEnable(true);

        if (!isExtract)
        {
            return;
        }
        
        GUILayout.BeginHorizontal();
        {
            fixSuperRoot = EditorGUILayout.ObjectField("所有_FixRoot的父节点：", fixSuperRoot, typeof(Transform)) as Transform;
            if (fixSuperRoot == null)
            {
                SetEnable(false);
            }
            if (GUILayout.Button("获取所有_FixRoot"))
            {
                InitFixRootsList();
            }
            SetEnable(true);

            if (fixRootsList == null || fixRootsList.Count == 0)
            {
                SetEnable(false);
            }
            if (GUILayout.Button("显示所有_FixRoot"))
            {
                SetFixRootsActive(true);
            }
            if (GUILayout.Button("隐藏所有_FixRoot"))
            {
                SetFixRootsActive(false);
            }
            SetEnable(true);
        }
        GUILayout.EndHorizontal();

        if (GUILayout.Button("4.创建BlendShapes模板（统一表情的名称、顺序，默认以结构最完全的头部为source）"))
        {
            CreateStructTemplate();
        }

        EditorGUILayout.BeginHorizontal();
        {
            structTemplate = EditorGUILayout.ObjectField("表情结构模板：", structTemplate, typeof(BlendShapesStructTemplate), SkinnProCustomUtility.ObjectFieldOption()) as BlendShapesStructTemplate;
            if (structTemplate)
            {
                if (GUILayout.Button("单独烘焙一个A52_Tongue_Out"))
                {
                    BakeA52TongueOut();
                }
            }
        }
        EditorGUILayout.EndHorizontal();

        if (structTemplate)
        {
            SkinnProCustomUtility.DrawColorLabel("请对表情结构模板进行调整，仅保留需要的BlendShapes，作为其子物体", Color.yellow);

            if (GUILayout.Button("5.模板调整完成，根据模板同步其他表情"))
            {
                SyncBlendShapesFromTemplate();
            }
        }
        else
        {
            SetEnable(false);
        }

        GUILayout.Space(10);

        if (GUILayout.Button("6.打开BlendShapes纠正窗口"))
        {
            var fixWindow = CC3BlendShapesFixWindow.OpenWindow();
            var fixInspector = fixWindow.GetInspector();
            fixInspector.fixRootsList = fixRootsList;
            fixInspector.blendshapeController = blendshapeController;

            shownOverrideWindow = true;
        }

        if (!shownOverrideWindow)
        {
            return;
        }

        GUILayout.Space(10);

        EditorGUILayout.BeginHorizontal();
        {
            if (GUILayout.Button("7.合并头部BlendShapes网格"))
            {
                CombineHeadMeshes();
            }

            if (GUILayout.Button("8.清理身体BlendShapes"))
            {
                ClearBodyBlendShapes();
            }

            if (GUILayout.Button("9.合并身体BlendShapes网格"))
            {
                CombineBodyMeshes();
            }
        }
        EditorGUILayout.EndHorizontal();
        
        SetEnable(true);
    }

    private void CombineBodyMeshes()
    {
        if (subMeshesList == null || subMeshesList.Count == 0)
        {
            subMeshesList = blendshapeController.GetComponentsInChildren<SkinnedMeshRenderer>(true).ToList();
        }

        CombineBlendShapesMeshes<CC3SubMeshBodyType>("合并身体BlendShapes网格",
           () =>
           {
               SkinnProCustomMain.CombineBlendShapesMesh();
               Selection.activeGameObject.name += "_Body";
           });

        ProgressUpdate();
    }

    private void ClearBodyBlendShapes()
    {
        if (subMeshesList == null || subMeshesList.Count == 0)
        {
            subMeshesList = blendshapeController.GetComponentsInChildren<SkinnedMeshRenderer>(true).ToList();
        }

        CombineBlendShapesMeshes<CC3SubMeshBodyType>("清理身体BlendShapes",
           () =>
           {
               SkinnProCustomMain.RemoveBlendShapes();
           });

        ProgressUpdate();
    }

    private void CombineHeadMeshes()
    {
        if (subMeshesList == null || subMeshesList.Count == 0)
        {
            subMeshesList = blendshapeController.GetComponentsInChildren<SkinnedMeshRenderer>(true).ToList();
        }

        CombineBlendShapesMeshes<CC3SubMeshHeadType>("合并头部BlendShapes网格",
            () =>
            {
                SkinnProCustomMain.CombineBlendShapesMesh();
                Selection.activeGameObject.name += "_Head";
            });

        ProgressUpdate();
    }

    /// <summary>
    /// 基于头部创建一个表情结构模板
    /// </summary>
    private void CreateStructTemplate()
    {
        var headRoot = GetFixRootsPoint(CC3SubMeshHeadType.Head);
        if (headRoot)
        {
            var headTemp = GameObject.Instantiate(headRoot.gameObject);
            headTemp.name = cc3ExportCharacter.name + "_StructTemplate";
            structTemplate = headTemp.AddComponent<BlendShapesStructTemplate>();
            structTemplate.gameObject.SetActive(true);
        }
        else
        {
            Debug.LogError("请手动复制Head_FixList，并添加<BlendShapesStructTemplate>组件");
        }

        ProgressUpdate();
    }

    /// <summary>
    /// 单独烘焙一个A52伸舌头的Mesh用于占位
    /// </summary>
    private void BakeA52TongueOut()
    {
        var headSkin = GetSkinnedMeshRendererInSubMesh(CC3SubMeshHeadType.Head);
        if (headSkin == null)
        {
            return;
        }

        Selection.activeObject = headSkin.gameObject;
        SkinnProCustomMain.Bake2MeshRenderer();

        var a52 = Selection.activeGameObject;
        if (a52)
        {
            a52.transform.SetParent(structTemplate.transform);
            a52.transform.SetAsLastSibling();
            a52.transform.localPosition = Vector3.zero;
            a52.name = "A52_Tongue_Out";
        }
    }

    /// <summary>
    /// 将表情结构模板中除了A开头的都移除掉
    /// </summary>
    private void RemoveExceptA_XX()
    {
        var blendShapesList = structTemplate.BlendShapesList;
        for (int i = blendShapesList.Count - 1; i >= 0; i--)
        {
            if (!blendShapesList[i].name.StartsWith("A") ||
                (blendShapesList[i].name[1] > '9'))
            {
                GameObject.DestroyImmediate(blendShapesList[i]);
            }
        }
        structTemplate.LoadShapes();
    }

    /// <summary>
    /// 从表情模板把结构同步到其他部位
    /// 若该部位原有表情 则按名字对应排序 清理掉多余的
    /// 若该部位没有表情 则烘焙默认Mesh 排序改名
    /// </summary>
    private void SyncBlendShapesFromTemplate()
    {
        var blendShapesList = structTemplate.BlendShapesList;
        using (var record = new SkinnProCustomUtility.TimeRecord("从表情模板把结构同步到其他部位"))
        {
            foreach (CC3SubMeshHeadType type in Enum.GetValues(typeof(CC3SubMeshHeadType)))
            {
                var fixRoot = GetFixRootsPoint(type);
                if (fixRoot == null)
                {
                    continue;
                }

                var subMesh = GetSkinnedMeshRendererInSubMesh(type);
                if (subMesh == null)
                {
                    continue;
                }

                if (fixRoot.childCount == 0) //无表情
                {
                    Selection.activeObject = subMesh;
                    SkinnProCustomMain.Bake2MeshRenderer();
                    var res = Selection.activeObject;
                    for (int i = 0; i < blendShapesList.Count; i++)
                    {
                        var part = GameObject.Instantiate(res) as GameObject;
                        part.name = blendShapesList[i].name;
                        part.transform.SetParent(fixRoot);
                        part.transform.localPosition = Vector3.zero;
                        part.transform.SetAsLastSibling();
                    }
                    GameObject.DestroyImmediate(res);
                }
                else //有表情
                {
                    var childrenList = fixRoot.GetAllChildren();
                    var removeList = new List<Transform>();
                    childrenList.ForEach((child) =>
                    {
                        if (!blendShapesList.Exists(go => go.name == child.name)) //如果这个节点模板里没有 就准备移除
                        {
                            removeList.Add(child);
                        }
                    });
                    removeList.ForEach(item => GameObject.DestroyImmediate(item.gameObject));
                    childrenList = fixRoot.GetAllChildren();
                    for (int i = blendShapesList.Count - 1; i >= 0; i--)
                    {
                        if (!childrenList.Exists(item => item.name == blendShapesList[i].name))
                        {
                            Selection.activeObject = subMesh;
                            SkinnProCustomMain.Bake2MeshRenderer();
                            var res = Selection.activeObject;
                            var part = GameObject.Instantiate(res) as GameObject;
                            part.name = blendShapesList[i].name;
                            part.transform.SetParent(fixRoot);
                            part.transform.localPosition = Vector3.zero;
                            part.transform.SetAsFirstSibling();
                            GameObject.DestroyImmediate(res);
                        }
                    }
                    SortChildren(fixRoot);
                }
            }
        }

        ProgressUpdate();
    }

    private void SortChildren(Transform parent)
    {
        if (parent == null || parent.childCount == 0)
        {
            return;
        }

        var children = parent.GetAllChildren();
        children.Sort((child1, child2) => { return child1.name.CompareTo(child2.name); });
        children.ForEach((child) =>
        {
            child.SetAsLastSibling();
        });
    }

    /// <summary>
    /// 提取所有SubMeshes的BlendShapes
    /// </summary>
    private void ExtractAllBlendShapes()
    {
        var extractTypes = Enum.GetNames(typeof(CC3SubMeshHeadType)); //需要被提取BlendShapes信息的部位 也就是头部相关的
        using (var record = new SkinnProCustomUtility.TimeRecord("提取所有SubMeshes的BlendShapes"))
        {
            for (int i = 0; i < extractTypes.Length; i++)
            {
                var smr = GetSkinnedMeshRendererInSubMesh(extractTypes[i]); //如果分割出来的SubMesh是需要被提取的
                if (smr == null)
                {
                    continue;
                }

                SkinnProCustomUtility.DisplayProgressBar(true, "提取BlendShapes", smr.name, (float)(i * 1f / extractTypes.Length));

                Selection.activeGameObject = smr.gameObject;
                var blendShapeMeshesList = SkinnProCustomMain.ExtractBlendShapes(smr.name);
                if (blendShapeMeshesList != null)
                {
                    var root = new GameObject(extractTypes[i] + "_FixList");

                    if (fixSuperRoot == null)
                    {
                        var fix = new GameObject(cc3ExportCharacter.name + "_FixSuperRoot");
                        fix.transform.position = Vector3.zero;
                        fixSuperRoot = fix.transform;
                    }

                    root.transform.SetParent(fixSuperRoot);
                    root.transform.localPosition = Vector3.zero;
                    for (int k = 0; k < blendShapeMeshesList.Count; k++)
                    {
                        blendShapeMeshesList[k].transform.SetParent(root.transform);
                        blendShapeMeshesList[k].transform.localPosition = Vector3.zero;
                    }
                    root.SetActive(false);
                    fixRootsList.Add(root.transform);
                }
            }

            SkinnProCustomUtility.DisplayProgressBar(false);
        }

        isExtract = true;

        ProgressUpdate();
    }

    /// <summary>
    /// 根据身体部位合成蒙皮
    /// 头部：直接合成
    /// 身体：清理掉BlendShapes信息再合成
    /// </summary>
    private void CombineBlendShapesMeshes<T>(string recordKey, Action callBack) where T : Enum
    {
        var extractTypes = Enum.GetNames(typeof(T));
        var selectsList = new List<GameObject>();
        using (var record = new SkinnProCustomUtility.TimeRecord(recordKey))
        {
            for (int i = 0; i < extractTypes.Length; i++)
            {
                var smr = GetSkinnedMeshRendererInSubMesh(extractTypes[i]);
                if (smr == null)
                {
                    continue;
                }

                selectsList.Add(smr.gameObject);
            }

            Selection.objects = selectsList.ToArray();
            callBack?.Invoke();
        }
    }

    private void SetFixRootsActive(bool enable)
    {
        for (int i = 0; i < fixRootsList.Count; i++)
        {
            fixRootsList[i].gameObject.SetActive(enable);
        }
    }

    /// <summary>
    /// 获取到所有FixRoot
    /// </summary>
    private void InitFixRootsList()
    {
        if (fixSuperRoot == null)
        {
            return;
        }

        if (fixRootsList != null && fixRootsList.Count != 0)
        {
            return;
        }

        fixRootsList.Clear();
        var childs = fixSuperRoot.GetAllChildren();
        for (int i = 0; i < childs.Count; i++)
        {
            if (childs[i].name.Contains("_FixList"))
            {
                fixRootsList.Add(childs[i]);
            }
        }
    }

    /// <summary>
    /// 根据节点类型获取到纠正节点的父物体
    /// </summary>
    private Transform GetFixRootsPoint(CC3SubMeshHeadType type)
    {
        for (int i = 0; i < fixRootsList.Count; i++)
        {
            if (fixRootsList[i].name.Contains(type.ToString()))
            {
                return fixRootsList[i];
            }
        }

        return null;
    }

    private MeshFilter GetFixMeshFilter(CC3SubMeshHeadType type, string name)
    {
        var root = GetFixRootsPoint(type);
        if (root == null)
        {
            return null;
        }

        return root.Get(name)?.GetComponent<MeshFilter>();
    }

    /// <summary>
    /// 从SubMeshList里面获取对应的蒙皮
    /// </summary>
    private SkinnedMeshRenderer GetSkinnedMeshRendererInSubMesh(string typeStr)
    {
        for (int i = 0; i < subMeshesList.Count; i++)
        {
            string halfName = subMeshesList[i].name.Remove(0, 11);
            if (halfName.Contains(typeStr))
            {
                return subMeshesList[i];
            }
        }

        return null;
    }

    private SkinnedMeshRenderer GetSkinnedMeshRendererInSubMesh(CC3SubMeshHeadType type)
    {
        return GetSkinnedMeshRendererInSubMesh(type.ToString());
    }

    /// <summary>
    /// 获取有效的身体部位Mesh.gameObject 注意一定要是GameObject
    /// </summary>
    private UnityEngine.Object[] GetVaildBodyPartObjs()
    {
        var vaildList = new List<UnityEngine.Object>();

        if (bodyMesh)
        {
            vaildList.Add(bodyMesh.gameObject);
        }
        if (eyeMesh)
        {
            vaildList.Add(eyeMesh.gameObject);
        }
        if (teethMesh)
        {
            vaildList.Add(teethMesh.gameObject);
        }
        if (tongueMesh)
        {
            vaildList.Add(tongueMesh.gameObject);
        }

        return vaildList.ToArray();
    }

    #region FixBlendShape

    /// <summary>
    /// 记录默认的根骨位置旋转等信息
    /// </summary>
    private void GetBonesDefaultInfo()
    {
        if (!bodyRoot)
        {
            return;
        }

        var bones = bodyRoot.GetAllChildren(true);
        bones.ForEach((bone) =>
        {
            bonePositionsList.Add(bone.localPosition);
            boneRotationsList.Add(bone.localRotation.eulerAngles);
        });
    }

    public void ResetBonesInfo()
    {
        if (!bodyRoot)
        {
            return;
        }

        var bones = bodyRoot.GetAllChildren(true);
        for (int i = 0; i < bones.Count; i++)
        {
            bones[i].localPosition = bonePositionsList[i];
            bones[i].localEulerAngles = boneRotationsList[i];
        }
    }

    public Transform GetBone(string name)
    {
        if (bodyRoot == null)
        {
            return null;
        }

        return bodyRoot.Get(name);
    }

    private void FixByDataConfig()
    {
        var fixDatasList = fixConfig.fixDatasList;
        foreach (var fixData in fixDatasList)
        {
            var bone = GetBone(fixData.fixBoneName);
            if (bone == null)
            {
                continue;
            }

            CC3BlendShapesFixWindow fixWindow = CC3BlendShapesFixWindow.OpenWindow();
            CC3BlendShapesFixInspector inspector = fixWindow.GetInspector();
            inspector.fixType = fixData.fixType;
            inspector.fixRoot = GetFixRootsPoint(fixData.fixType);
            inspector.fixRootsList = fixRootsList;
            inspector.blendshapeController = blendshapeController;
            inspector.fixSkinMeshRenderer = GetSkinnedMeshRendererInSubMesh(fixData.fixType);
            inspector.AutoExecute(fixData, bone);
            CC3BlendShapesFixWindow.CloseWindow();
        }

        ProgressUpdate();
    }

    private void ClearTemp()
    {
        GameObject.DestroyImmediate(blendshapeController.gameObject);
        GameObject.DestroyImmediate(fixSuperRoot.gameObject);
        GameObject.DestroyImmediate(structTemplate.gameObject);

        blendshapeController = null;
        fixSuperRoot = null;
        structTemplate = null;
        SkinnProCustomUtility.TempRoot = null;
    }

    #endregion
}
